﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cesave.Domain.PermisosModule.Entities;
using System.ComponentModel;
using Cesave.Domain.PermisosModule.Contracts.Modulos;
using Cesave.Infrastructure.CrossCutting.IoC;
using System.Windows.Forms;

namespace Cesave.DistributedServices.PermisosModule.WindowsHost.ViewModels.Catalogs.Secciones
{
	public partial class SeccionesViewModel
	{
		#region Private properties

		/// <summary>
		/// 
		/// </summary>
		private List<Modulo> _modulos;

		/// <summary>
		/// 
		/// </summary>
		private Modulo _modulo;

		#endregion

		#region Public properties

		/// <summary>
		/// 
		/// </summary>
		public List<Modulo> Modulos
		{
			get
			{
				return _modulos;
			}
			private set
			{
				_modulos = value;
				if (_modulos != null)
					RaisePropertyChanged("Modulos");
			}
		}

		/// <summary>
		/// 
		/// </summary>
		public Modulo Modulo
		{
			get
			{
				return _modulo;
			}
			private set
			{
				_modulo = value;
				if (_modulo != null)
					RaisePropertyChanged("Modulo");
			}
		}

		#endregion

		#region Private methods

		/// <summary>
		/// 
		/// </summary>
		private void LoadModulos()
		{
			StartWaiting();
			using (BackgroundWorker worker = new BackgroundWorker())
			{
				worker.DoWork += (sender, e) =>
				{
					IModuloService service = IoCFactory.Resolve<IModuloService>();
					e.Result = service.FindModulosByJunta(Junta.JuntaGuid);
				};
				worker.RunWorkerCompleted += (sender, e) =>
				{
					EndWaiting();
					if (!e.Cancelled && e.Error == null)
						Modulos = e.Result as List<Modulo>;
					else if (e.Error != null)
						ShowMessage(e.Error.Message);
				};
				worker.WorkerSupportsCancellation = true;
				worker.RunWorkerAsync();
			}
		}

		#endregion

		#region Event methods

		/// <summary>
		/// 
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void SetCurrentModulo(object sender, EventArgs e)
		{
			BindingSource bindingSource = sender as BindingSource;
			if ((bindingSource != null) && (bindingSource.Current != null))
				Modulo = bindingSource.Current as Modulo;
		}

		/// <summary>
		/// 
		/// </summary>
		private void OnModulosPropertyChanged()
		{
			_view.modulosBindingSource.DataSource = Modulos;
			_view.modulosBindingSource.CurrentChanged += SetCurrentModulo;
			SetCurrentModulo(_view.modulosBindingSource, new EventArgs());
		}

		/// <summary>
		/// 
		/// </summary>
		private void OnModuloPropertyChanged()
		{
			LoadSecciones();
		}

		#endregion

	}
}
